package services

import (
	"TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/internal/admin/services"
	appdao "TaskAssignmentSystem/internal/app/dao"
	"fmt"
)

type UserMessageService struct {
}

func (s *UserMessageService) CheckUserHasUnreadMessage(id uint) (exist bool, err error) {
	var messageDao dao.Common[dao.UserMessage]
	if count, err := messageDao.Count(map[string]interface{}{"system_user_id": id, "status": 0}); err != nil {
		return false, err
	} else {
		if count == 0 {
			return false, nil
		} else {
			return true, nil
		}
	}
}

func (s *UserMessageService) CheckUserProjectHasUnreadMessage(id uint, projectId string) (exist bool, count int64, err error) {
	var messageDao dao.Common[dao.UserMessage]
	if count, err := messageDao.Count(map[string]interface{}{"system_user_id": id, "project_id": projectId, "status": 0}); err != nil {
		return false, count, err
	} else {
		if count == 0 {
			return false, count, nil
		} else {
			return true, count, nil
		}
	}
}

func (s *UserMessageService) CheckUserProjectHasUnreadMessageNew(id uint, projectId string) (exist bool, count int64, err error) {
	var messageDao services.CommonService[dao.UserMsgInfo]
	var userDao dao.Common[dao.SystemUser]
	if user, err := userDao.First(map[string]interface{}{"id": id}); err != nil {
		return false, count, err
	} else {
		messageDao.LeftJoin = append(messageDao.LeftJoin, fmt.Sprintf("left join tas_system_msg m on tas_user_msg_info.msg_id = m.id"))
		messageDao.WhereStr = append(messageDao.WhereStr, fmt.Sprintf("tas_user_msg_info.system_user_id = '%v'", user.UserId))
		messageDao.WhereStr = append(messageDao.WhereStr, fmt.Sprintf("tas_user_msg_info.status = 0"))
		messageDao.WhereStr = append(messageDao.WhereStr, fmt.Sprintf("m.permissions = '%v'", projectId))
		if list, err := messageDao.FindWithLeftJoinAll(); err != nil {
			return false, 0, err
		} else {
			if len(list) == 0 {
				return false, 0, nil
			} else {
				return true, int64(len(list)), nil
			}
		}
	}
}

func (s *UserMessageService) CheckUserProjectHasUnreadMessageNew2(user appdao.SystemUser, projectId string) (exist bool, count int64, err error) {
	var messageDao services.CommonService[dao.UserMsgInfo]
	messageDao.LeftJoin = append(messageDao.LeftJoin, fmt.Sprintf("left join tas_system_msg m on tas_user_msg_info.msg_id = m.id"))
	messageDao.WhereStr = append(messageDao.WhereStr, fmt.Sprintf("tas_user_msg_info.system_user_id = '%v'", user.UserId))
	messageDao.WhereStr = append(messageDao.WhereStr, fmt.Sprintf("tas_user_msg_info.status = 0"))
	messageDao.WhereStr = append(messageDao.WhereStr, fmt.Sprintf("m.permissions = '%v'", projectId))
	if list, err := messageDao.FindWithLeftJoinAll(); err != nil {
		return false, 0, err
	} else {
		if len(list) == 0 {
			return false, 0, nil
		} else {
			return true, int64(len(list)), nil
		}
	}

}
